package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SecKillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSesssionsWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SecKillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1、扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLates3DaySession();
        if (session.getCode() == 0){
            //上架商品
            List<SeckillSesssionsWithSkus> sessionData = session.getData(new TypeReference<List<SeckillSesssionsWithSkus>>() {});

            // 缓存到redis
            // 1、缓存活动信息
            saveSessionInfos(sessionData);
            // 2、缓存活动关联的商品信息
            saveSessionSkuInfos(sessionData);
        }
    }

    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        Set<String> keys = hashOps.keys();
        if (null != keys && keys.size() > 0){
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx,key)){
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    // TODO 加入非空判断
                    if (skuRedisTo == null) {
                        return null;
                    }
                    long current = System.currentTimeMillis();
                    if (current >= skuRedisTo.getStartTime() && current <= skuRedisTo.getEndTime()) {
                        //TODO
                    } else {
                        //TODO 当前商品已经过了秒杀时间要直接删除
                        hashOps.delete(key);
                        skuRedisTo.setRandomCode(null);
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * 入参可以原函数的参数，和BlockException
     * @param e
     * @return
     */
    public List<SecKillSkuRedisTo> blockHandler(BlockException e){
        log.error("getCurrentSeckillSkusResources被限流了。。。。。。");
        return null;
    }
    @Override
    // blockHandler 函数会在原方法被限流、降级、系统保护的时候调用，而fallback函数会针对所有类型的异常
    @SentinelResource(value = "getCurrentSeckillSkusResources",blockHandler = "blockHandler")
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {

        //1、确定当前时间属于哪个秒杀场次。
        //1970 -
        long time = System.currentTimeMillis();
        try(Entry entry = SphU.entry("SeckillSkus")) {
            // 查到所有秒杀活动的key
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                //seckill:sessions:1582250400000_1582254000000
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] s = replace.split("_");
                Long start = Long.parseLong(s[0]);
                Long end = Long.parseLong(s[1]);
                if (time >= start && time <= end) {
                    //2、获取这个秒杀场次需要的所有商品信息
                    List<String> range = redisTemplate.opsForList().range(key, -100, 100);// 获取list集合中-100到正100的商品 其实是从0开始的
                    BoundHashOperations<String, String, String> hashops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                    List<String> list = hashops.multiGet(range);// 从hash里取出range集合个key的值
                    if (null != list && list.size() > 0){
                        List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                            SecKillSkuRedisTo secKillSkuRedisTo = JSON.parseObject(item, SecKillSkuRedisTo.class);
                            //                        redis.setRandomCode(null); 当前秒杀开始就需要随机码
                            return secKillSkuRedisTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }
        }catch (BlockException e){
            log.error("资源被限流，{}",e.getMessage());
        }
        return null;
    }
    // TODO 上架秒杀商品的时候，每一个数据都有过期时间。
    // TODO 秒杀后续的流程，简化了收货地址等信息。
    @Override
    public String kill(String killId, String key, Integer num) {

        long s1 = System.currentTimeMillis();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        // 1、获取现在正在秒杀的商品信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (!StringUtils.isEmpty(json)){
            SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
            // 教研合法性
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = System.currentTimeMillis();

            long ttl = endTime - startTime;
            // 1、校验时间的合法性
            if (time >= startTime && time <= endTime){
                // 2、校验随机码和商品id
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)){
                    // 3、验证购物数量是否合理
                    if (num <= redis.getSeckillLimit()){
                        // 4、验证这个人是否已经购买过。幂等性；  如果只要秒杀成功，就去占位。 userId_sessionId_skuId
                        // SETNX
                        String redisKey = memberRespVo.getId() + "_" + skuId;
                        // 自动过期  key值没有才创建   且创建的有效期到秒杀时间结束
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            // 占位成功说明从来没有买过  扣减信号量
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            // 120 20ms
                            /*try {
                                boolean acquire = semaphore.tryAcquire(num,100,TimeUnit.MILLISECONDS); // 试着获取信号量
                                if (acquire){// 秒杀成功 快速下单
                                    String timeId = IdWorker.getTimeId();
                                    SecKillOrderTo orderTo = new SecKillOrderTo();
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(memberRespVo.getId());
                                    orderTo.setNum(num);
                                    orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                    orderTo.setSkuId(redis.getSkuId());
                                    orderTo.setSeckillPrice(redis.getSeckillPrice());
                                    // 只发送rabbitMQ消息 不监听rabbitMQ的消息 可以不用开启@EnableRabbit注解
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order", orderTo);
                                    long s2 = System.currentTimeMillis();
                                    log.info("耗时...{}", (s2 - s1));
                                    return timeId;
                                }
                            } catch (InterruptedException e) {
                                return null;
                            }*/

                            boolean acquire = semaphore.tryAcquire(num); // 试着获取信号量 不等待  不用抛出异常
                            if (acquire){// 秒杀成功 快速下单
                                String timeId = IdWorker.getTimeId();
                                SecKillOrderTo orderTo = new SecKillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(memberRespVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                // 只发送rabbitMQ消息 不监听rabbitMQ的消息 可以不用开启@EnableRabbit注解
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order", orderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("耗时...{}", (s2 - s1));
                                return timeId;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionSkuInfos(List<SeckillSesssionsWithSkus> sessionData) {
        if (sessionData != null){
            sessionData.forEach(session -> {
                long startTime = session.getStartTime().getTime();
                long endTime = session.getEndTime().getTime();
                String key = SESSIONS_CACHE_PREFIX + startTime +  "_" + endTime;
                if (!redisTemplate.hasKey(key)){ // 解决幂等性  若没有该活动  就加入到缓存
                    // 收集场次id_商品id集合
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                    // 缓存活动信息
                    redisTemplate.opsForList().leftPushAll(key,collect);
                }
            });
        }
    }

    private void saveSessionInfos(List<SeckillSesssionsWithSkus> sessionData) {

        sessionData.stream().forEach(sessions -> {
            // 准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            sessions.getRelationSkus().stream().forEach(seckillSkuVo -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                // 将场次id_商品id作为存sku的key
                if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())){
                    // 缓存商品
                    SecKillSkuRedisTo skuRedisTo = new SecKillSkuRedisTo();
                    // 1、sku的基本信息
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (skuInfo.getCode() == 0){
                        SkuInfoVo info = skuInfo.getData("skuI nfo", new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfo(info);
                    }
                    // 2、sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo,skuRedisTo);
                    // 3、设置上当前商品的秒杀时间信息
                    skuRedisTo.setStartTime(sessions.getStartTime().getTime());
                    skuRedisTo.setEndTime(sessions.getEndTime().getTime());
                    //4、随机码？  seckill?skuId=1&key=dadlajldj；
                    skuRedisTo.setRandomCode(token);

                    String jsonstr = JSON.toJSONString(skuRedisTo);
                    ops.put(ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString()),jsonstr);
                    // 5、使用库存作为分布式的信号量   信号量的最大作用就是限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
